//
//  String+Extension.swift
//  ReportScan
//
//  Created by woniu on 2025/7/23.
//

import Foundation

extension String{
    ///正则是否匹配，正则匹配，正则校验
    func isMatch(pattern: String) -> Bool {
        let regexObj = try? NSRegularExpression(pattern: pattern, options:[])
        let matches = regexObj?.matches(in: self, options: [], range: NSRange(self.startIndex...,in: self)) ?? []
        return !matches.isEmpty
    }
    
    
    ///正则，找出指定字符串
    func regexGetSub_(pattern:String) -> [String] {
        var subStr:[String] = []
        let regex = try? NSRegularExpression(pattern: pattern, options:[])
        if let regexPar = regex{
            let matches = regexPar.matches(in: self, options: [], range: NSRange(self.startIndex...,in: self))
            for  match in matches {
                let matchStr = (self as NSString).substring(with: match.range)
                subStr.append(matchStr)
            }
        }
        
        return subStr
    }
    ///是否是正整纯数字
    func isNum()->Bool{
        let regex = "\\d+"
        let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
        return predicate.evaluate(with:self)
    }
    
    ///是否是数字(包含小数)
    func isDoubNum()->Bool{
        let regex = "^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*$"
        let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
        let v = predicate.evaluate(with:self)
        return v
    }
    static let pubNumberFormatter = NumberFormatter()
    ///转CGFloat
    func floatValue() -> Float{
        if let num = String.pubNumberFormatter.number(from: self) {
            return num.floatValue
        } else {
            return 0
        }
    }
    
    
    //JSONString转换为数组
    func getArrayFromJSONString() ->[Any]{
        guard let jsonData:Data = self.data(using: .utf8) else{
            return []
        }
        if let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? [Any] {
            return array
        }
        return []
    }
    
    ///身份证中间隐藏显示  身份证脱敏
    func toIdCardHidden() -> String{
        
        var tempString = self
        if tempString.count == 18 {
            
            let startIndex = tempString.index(self.startIndex, offsetBy: 6)
            let endIndex = tempString.index(self.startIndex, offsetBy: 14)
            let range  = startIndex...endIndex
            tempString.replaceSubrange(range, with: "*********")
            return tempString
        }
        
        return tempString
    }
    ///去掉所有空格
    var removeAllSapce: String {
        return self.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
    }
    ///自定义转整数
    func intValue(replace:Int = 0)->Int{
        if self == ""{return replace}
        if let num = String.pubNumberFormatter.number(from: self) {
            return num.intValue
        } else {
            return replace
        }
    }
    
    /// 转double
    public func doubleValue() -> Double {
        if let num = String.pubNumberFormatter.number(from: self) {
            return num.doubleValue
        } else {
            return 0.0
        }
    }
    
    ///比较字符串大小 （当前字符串 ： 目标字符串）
    func compar(_ objString:String)->Int{
        let bool = self.compare(objString)
        if bool == ComparisonResult.orderedAscending{
            return -1
        }else if bool == ComparisonResult.orderedDescending{
            return 1
        }
        return 0//相等
    }
    
    /// 截取到任意位置
    func subString(to: Int) -> String {
        if to > self.count{
            return self
        }
        let index: String.Index = self.index(startIndex, offsetBy: to)
        return String(self[..<index])
    }
    
    /// 从任意位置开始截取
    func subString(from: Int) -> String {
        let index: String.Index = self.index(startIndex, offsetBy: from)
        return String(self[index ..< endIndex])
    }
    
    /// 从任意位置开始截取到任意位置 (包含to )
    func subString(from: Int, to: Int) -> String {
        let beginIndex = self.index(self.startIndex, offsetBy: from)
        let endIndex = self.index(self.startIndex, offsetBy: to)
        return String(self[beginIndex...endIndex])
    }
    
    ///String 转 字典
    func toDic()->[String:Any]{
        if self.isEmpty{return[:]}
        guard let data = self.data(using: String.Encoding.utf8)else{return [:]}
        var tempDic:[String:Any] = [:]
        if let dict = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String : Any] {
            tempDic = dict
        }
        if !tempDic.isEmpty{return tempDic}
        //字符串里的字符串转dic
        guard let dic = try? JSONSerialization.jsonObject(with:data, options: .allowFragments) as? [String:Any] ?? [:] else {
            let beginStr = "\"{"
            let endStr = "}\""
            let str = self
            if str.hasPrefix(beginStr) && str.hasSuffix(endStr){
                let subStr = str.subString(from: 1, to: 2)
                guard let vDic = try? JSONSerialization.jsonObject(with: subStr.data(using: .utf8)!, options: .allowFragments) as? [String:Any] ?? [:] else {
                    return [:]
                }
                return vDic
            }
            
            return [:]
        }
        return dic
    }
    
    ///移除最后个符号
    func removeLastChart(_ chart:String)->String{
        var str =  self
        if str.hasSuffix(chart){
            str.removeLast()
        }
        return str
    }
    
    ///是否包含指定字符串
    public func contain(_ subStr:String)->Bool{
        return self.contains(subStr)
    }
    
    
    // 身份证正则检查
    func isIDCardNum() -> Bool
    {
        let regx = "^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$"
        if (self.isMatch(pattern: regx))
        {
            var sum:Int = 0
            var mutiArr:[Int] = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
            let regArr:[String] = ["1","0","X","9","8","7","6","5","4","3","2"]
            var newSr:String = self
            let regStr:String = String(newSr.removeLast())
            for _ in 0...16 {
                let strChar:String = String.init(newSr.removeLast())
                let numChar:Int = Int.init(strChar)!
                let numMuti:Int = mutiArr.popLast()!
                sum = sum + numChar * numMuti
            }
            let modResult:Int = sum % 11
            let resultStr:String = regArr[modResult]
            if (resultStr == regStr || resultStr == regStr.uppercased()) {
                return true
            }else {
                return false
            }
        }
        else
        {
            return false
        }
    }
}
